package com.edu.lighthouse.service;

import com.alibaba.druid.util.StringUtils;
import com.edu.lighthouse.helper.security.Encryption;
import com.edu.lighthouse.helper.security.Jwt;
import com.edu.lighthouse.mapper.UserMapper;
import com.edu.lighthouse.pojo.User;
import com.edu.lighthouse.pojo.vo.UserBaseVo;
import com.edu.lighthouse.pojo.vo.UserRegVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 用户类逻辑处理
 *
 * @author jinzc
 */
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public List<UserRegVo> list(UserBaseVo userBaseVo){
        return userMapper.list(userBaseVo);
    }

    public Integer register(User user) {
        user.setPass(Encryption.hash(user.getPass()));
        return userMapper.register(user);
    }

    public UserRegVo login(String name, String pass) {
        UserRegVo userRegVo = userMapper.selectByName(name);
        if (Objects.isNull(userRegVo)) {
            return null;
        }
        boolean result = Encryption.checkPass(pass, userRegVo.getPass());
        if (!result) {
            return null;
        }
        String token = Jwt.sign(userRegVo.getId().toString());
        userRegVo.setToken(token);
        userRegVo.setPass(null);
        return userRegVo;
    }

    public Integer resetPass(Integer userId) {
        User user = new User();
        user.setId(userId);
        user = userMapper.selectOne(user);
        if(StringUtils.isEmpty(user.getName())){
            return 0;
        }
        user.setPass(Encryption.hash("123456"));
        return userMapper.updateByPrimaryKey(user);
    }

    public Integer updateUserState(Integer userId,Integer delFlag) {
        User user = new User();
        user.setId(userId);
        user = userMapper.selectOne(user);
        if(StringUtils.isEmpty(user.getName())){
            return 0;
        }
        user.setDelFlag(delFlag);
        return userMapper.updateByPrimaryKey(user);
    }
}
